package com.example.moban.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
//import com.baidu.location.BDAbstractLocationListener;
//import com.baidu.location.BDLocation;
//import com.baidu.location.LocationClient;
//import com.baidu.location.LocationClientOption;
import com.example.moban.R;
import com.example.moban.api.HuRequest;
import com.example.moban.application.MyApplication;
import com.example.moban.base.BaseActivity;
import com.example.moban.base.PhoneTypeBean;
import com.example.moban.beans.LocationBean;
import com.example.moban.constants.Constants;
import com.example.moban.module.VersionUpdateModule;
import com.liuwan.datetimepicker.DateFormatUtils;


import com.rzhd.coursepatriarch.common.api.base.BaseObserver;
import com.rzhd.coursepatriarch.common.constants.HttpConstants;
import com.rzhd.coursepatriarch.common.utils.CommonUtil;
import com.rzhd.coursepatriarch.common.utils.permission.AndPermissionUtils;


import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author huling
 * @date: 2019/1/15.
 */
public class SplashActivity extends BaseActivity implements VersionUpdateModule.OnInterceptListener,
        AndPermissionUtils.AddPermissionCallback {

    @BindView( R.id.activity_splash_version_text )
    AppCompatTextView currentVersionText;
    @BindView( R.id.activity_splash_count_time_text )
    AppCompatTextView countTimeText;

//    private VersionUpdateModule versionUpdateModule;
    private AndPermissionUtils mPermissionUtils;
    /**
     * 是否执行授权方法
     */
    private boolean isExecGrant;
    private HuRequest huRequest;
//    private MyLocationListener listener = new MyLocationListener();
//    private LocationClient locationClient;//百度地图
    private LocationBean bean;
    private boolean isIntercept = true;

    @Override
    public void setContentView(Bundle savedInstanceState) {
        setContentView( R.layout.activity_splash_layout );
        super.isAddConnectListener = false;
        ((MyApplication)getApplication()).splash=this;
        initHttpConstants();
    }

    /**
     * 初始化请求相关值
     */
    private void initHttpConstants(){
        HttpConstants.BASE_HOST = CommonUtil.getApplicationMetaValue(this, "ENVIRONMENT");
        HttpConstants.PRODUCT_NAME = CommonUtil.getApplicationMetaValue(this, "PRODUCT_NAME");
        HttpConstants.BASE_URL = HttpConstants.BASE_HOST + HttpConstants.PRODUCT_NAME;
    }

    @Override
    public void initView() {

        mCustomToolbar.setVisibility( View.GONE );
        huRequest = new HuRequest( );
        initBaiduLocation();
        requestFulScreen( false , true , true );
        createBottomText();
//        versionUpdateModule = new VersionUpdateModule( this , this );
        mPermissionUtils = new AndPermissionUtils( this , this );
//        versionUpdateModule.setShowProgress( false );
//        versionUpdateModule.setInterceptListener( this );
        //获取设备唯一标识
        preferenceUtils.getDeviceCodeAndSave();
//        getPhoneTypeList();
        mPermissionUtils.requestPermission(AndPermissionUtils.splashPermissions);

    }

    /**
     * 百度初始化定位
     */
    private void initBaiduLocation(){
//        locationClient = new LocationClient( this );
//        LocationClientOption option = new LocationClientOption();
//        //默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
//        //POI就是获取到的位置附近的一些商场、饭店、银行等信息
//        option.setIsNeedLocationPoiList(false);
//        option.setIsNeedAddress(true);
//        //可选，是否需要地址信息，默认为不需要，即参数为false
//        //如果开发者需要获得当前点的地址信息，此处必须为true
//
//        locationClient.setLocOption(option);
//        //mLocationClient为第二步初始化过的LocationClient对象
//        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
//        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
//        locationClient.registerLocationListener( listener );
    }

    private void createBottomText(){
        String date = DateFormatUtils.long2Str(Calendar.getInstance().getTime().getTime(), DateFormatUtils.DATE_FORMAT_PATTERN_YM);
        String versionName = CommonUtil.getVersionName(this);
        currentVersionText.setText( date + " V" + versionName );
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch ( msg.what ){
                case Constants.MessageConstants.SPLASH_MESSAGE_WHAT:
                    getAdvertisingDatas();
                    break;
            }
        }
    };


    @Override
    public void onIntercept(boolean isIntercept) {
        this.isIntercept = isIntercept;
        if( !isIntercept ){
            handler.sendEmptyMessage( Constants.MessageConstants.SPLASH_MESSAGE_WHAT );
        }
    }

    @Override
    public void downloadResult(boolean isSuccess) {

    }

    @Override
    public void onBack() {

    }

    @Override
    protected void onResume() {
        super.onResume();

    }


    @Override
    protected void onRestart() {
        super.onRestart();
//        if( versionUpdateModule != null && !versionUpdateModule.isForce() && isExecGrant ){
//            handler.sendEmptyMessage( Constants.MessageConstants.SPLASH_MESSAGE_WHAT );
//        }
        if( isExecGrant ){
            handler.sendEmptyMessage( Constants.MessageConstants.SPLASH_MESSAGE_WHAT );
        }
    }

    @Override
    public void onGranted(@NonNull List<String> permissions) {
//        if( !isExecGrant ){
//            versionUpdateModule.checkVersion( false );
//        }
//        isExecGrant = true;
        handler.sendEmptyMessage( Constants.MessageConstants.SPLASH_MESSAGE_WHAT );
        //百度开始定位
//        locationClient.start();
    }

    @Override
    public void onDenied(@NonNull List<String> permissions) {

    }

    @Override
    public void onComeback() {

    }

    @Override
    public void initData() {
    }

    @Override
    public void onClick(View v) {
    }

    @OnClick({ R.id.activity_splash_count_time_text })
    public void handleClickEvent( View view ){
        switch ( view.getId() ){
            case R.id.activity_splash_count_time_text:
                if( !isIntercept ){
                    handler.sendEmptyMessage( Constants.MessageConstants.SPLASH_MESSAGE_WHAT );
                }
                break;
        }
    }

    /**
     * 获取手机型号
     */
    public void getPhoneTypeList(){
        huRequest.getPhoneTypeList(new BaseObserver<String>( this , false ) {
            @Override
            public void onNext(String json) {
                try {
                    if (TextUtils.isEmpty(json)) {
                        return;
                    }
                    PhoneTypeBean bean = JSON.parseObject(json, PhoneTypeBean.class);
                    if (bean == null) {
                        return;
                    }
                    if (bean.getCode() == HttpConstants.RESPONSE_CODE_200) {
                        List<PhoneTypeBean.DataBean> data = bean.getData();
                        if (data == null || data.size() <= 0) {
                            return;
                        }
                        MyApplication.getMyApplicationInstance().setPhoneTypeList(data);
                    }
                } catch (Exception e) {
                }
            }
        });
    }

    /**
     * 获取广告数据
     */
    public void getAdvertisingDatas(){
//        Map<String, Object> params = new HashMap<>();
////        current	是	Integer	当前页
////        size	是	Integer	页大小
//        params.put( "current" , "1" );
//        params.put( "size" , 1 );
//        //1-家长端 2-教师端
//        params.put( "type" , "1" );
//        huRequest.getStartPageApiList( params , new BaseObserver<String>( this , false ) {
//            @Override
//            public void onNext(String json) {
//                if( TextUtils.isEmpty( json )){
//                    toNextPage();
//                    return;
//                }
//                AdvertisingBean bean = JSON.parseObject( json , AdvertisingBean.class );
//                if( bean == null ){
//                    toNextPage();
//                }
//                if( bean.getCode() == HttpConstants.RESPONSE_CODE_200 ){
//                    if( bean.getData() == null || bean.getData() == null || bean.getData().getList() == null || bean.getData().getList().size() <= 0 ){
//                        toNextPage();
//                        return;
//                    }
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable( "data" , bean.getData() );
//                    showActivity( AdvertisingActivity.class , bundle );
//                    finish();
//                }else{
                        new  Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                toNextPage();
                            }
                        },1000);

//                }
//            }
//        });
    }

    private void toNextPage(){
        //如果已经登录则直接跳转到首页，否则跳转到登录页面
//        if( preferenceUtils.getLogin() ){
            showActivity( MainActivity.class );
            finish();
//        }else{
//            Bundle bundle = new Bundle();
//            bundle.putString( "fromClass" , SplashActivity.class.getSimpleName() );
//            bundle.putBoolean( "isBindPhone" , false );
////            showActivity( LoginActivity.class , bundle );
//            showActivity( SecondLoginActivity.class , bundle );
//            finish();
//        }
    }



    //百度定位
//    public class MyLocationListener extends BDAbstractLocationListener {
//        @Override
//        public void onReceiveLocation(BDLocation location){
//            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
//            //以下只列举部分获取地址相关的结果信息
//            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
//
//            try{
//                String addr = location.getAddrStr();    //获取详细地址信息
//                String country = location.getCountry();    //获取国家
//                String province = location.getProvince();    //获取省份
//                String city = location.getCity();    //获取城市
//                String district = location.getDistrict();    //获取区县
//                String street = location.getStreet();    //获取街道信息
//
////                List<Poi> poiList = location.getPoiList();
//                if( bean == null ){
//                    bean = new LocationBean();
//                }
//                //获取周边POI信息
//                //POI信息包括POI ID、名称等，具体信息请参照类参考中POI类的相关说明
//                bean.setAddr( addr );
//                bean.setCity( city );
//                bean.setCountry( country );
//                bean.setProvince( province );
//                bean.setDistrict( district );
//                bean.setStreet( street );
//                String string = JSON.toJSONString(bean);
//                preferenceUtils.saveLocationDatas( string );
//            }catch ( Exception e ){
//            }
//        }
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        if( locationClient != null ){
//            locationClient.stop();
//        }
//    }
}